package com.ponxu.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 简单配置文件读写类, 只支持key=value单行
 * 
 * @author xwz
 * 
 */
public class Properties {
	private Map<String, Property> props;

	public void load(InputStream in) throws IOException {
		props = new LinkedHashMap<String, Property>();
		BufferedReader br = new BufferedReader(new InputStreamReader(in));

		String line = null;
		List<String> comments = new ArrayList<String>();
		while ((line = br.readLine()) != null) {
			System.out.println("line: " + line);
			if ("".equals(line) || line.startsWith("#")) {
				comments.add(line);
			} else {
				int i = line.indexOf("=");
				if (i == -1) {
					throw new RuntimeException("Error line: " + line);
				}
				String key = line.substring(0, i);
				String value = line.substring(i + 1);

				System.out.println("key=" + key + " value=" + value);

				Property p = new Property(key, value);
				p.comments = comments;
				props.put(key, p);

				comments = new ArrayList<String>();
			}
		}
		br.close();
	}

	public void save(OutputStream out) throws IOException {
		PrintWriter pw = new PrintWriter(out);

		for (String key : props.keySet()) {
			System.out.println("write key=" + key);
			Property p = props.get(key);
			List<String> comments = p.comments;
			if (comments != null) {
				for (String c : comments) {
					pw.println(c);
				}
			}
			pw.println(String.format("%s=%s", p.key, p.value));
		}

		pw.flush();
		pw.close();
	}

	public String getProperty(String key) {
		Property p = props.get(key);
		if (p != null) {
			return p.value;
		}
		return null;
	}

	public String setProperty(String key, String value) {
		Property p = props.get(key);
		String old = null;
		if (p != null) {
			old = p.value;
			p.value = value;
		} else {
			p = new Property(key, value);
			props.put(key, p);
		}
		return old;
	}

	public void setComment(String key, String comment) {
		Property p = props.get(key);
		if (p != null) {
			p.addComment(comment);
		}
	}

	private static class Property {
		String key;
		String value;
		List<String> comments;

		public Property(String key, String value) {
			this.key = key;
			this.value = value;
		}

		public void addComment(String comment) {
			if (comments == null) {
				comments = new ArrayList<String>();
			}
			comments.add(comment);
		}
	}
}